package com.trs.publish.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.internal.lang.annotation.ajcDeclareAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.trs.publish.aspect.Description;
import com.trs.publish.aspect.OperationDesc;
import com.trs.publish.domain.User;
import com.trs.publish.service.UserService;


/**
 * 密码管理
 * @author jia.haihong
 *
 */

@Controller
public class PasswordController{ 
	
	private static final Logger logger = LoggerFactory.getLogger(PasswordController.class);

	@Autowired 
	private UserService userService;
	
	@RequestMapping(value = "/toPassword")
    public ModelAndView toUser(ModelAndView model,HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		String password = user.getPassword();
		user.setPassword2(user.getPassword());
		model.addObject(user);
		model.setViewName("password/detail");
        return model;
    }  
	
	/**
	 * 更新密码
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping(value = "/password")
	@ResponseBody
	@OperationDesc(description = Description.Update_password)
	public ModelAndView updatePassword(ModelAndView model,@Valid User user, BindingResult result) {
		String password = user.getPassword();
		String password2 = user.getPassword2();
		if(StringUtils.isNoneEmpty(password)&&StringUtils.isNoneEmpty(password2)) {
			   if(password.equals(password2)) {
					  BCryptPasswordEncoder encode = new BCryptPasswordEncoder(4); 
						 long id = user.getId();
						String aa = "system";
						String hashPass1 = encode.encode(aa);
						
						//password加密
					    String hashPass = encode.encode(password);
					    
					    //更新用户
						User u = new User();
						u.setId(id);
						u.setPassword(hashPass);
						u.setLastactivetime(new Date());
						userService.update(u);
				        model.addObject("MSG", "更新成功！");
				    }else {
					    model.addObject("MSG", "两次密码输入不同，请重新输入");
			 		}
		}
		model.setViewName("password/detail");
		return model;
	}
}

